#include <stdlib.h>
#include <string.h>

static int N = 0, *prime = NULL;

void
sieve_init(int n)
{
    int i, j;

    prime = malloc(sizeof(int) * n);
    if (prime == NULL)
        return;

    N = n;
    memset(prime, 1, sizeof(int) * n);
    for (i = 2; i < N; ++i) {
        while (!prime[i]) {
            ++i;
            if (i == N)
                return;
        }
        prime[i] = 1;
        for (j = i * i; j < N; j += i)
            prime[j] = 0;
    }
}

void
sieve_finalize()
{
    if (prime != NULL)
        free(prime);
}

int
is_prime(int i)
{
    if (prime == NULL || i > N)
        return 0;

    return prime[i];
}
